import apis from '../apis'
import Taro from '@tarojs/taro'
import { getBaseUrl } from './utils'
function params(url, query) {
  let res = ''
  if (/\{([\d\w_-]+)\}/g.test(url)) {
    res = url.replace(/\{([\d\w_-]+)\}/g, (word, $1) => {
      const res = query[$1] || ''
      return res
    })
    return res
  } else {
    return null
  }
}

const $ajax = {
  get: function (url, query) {
    const reallyUrl = params(apis[url].url, query)
    console.log(reallyUrl)
    return this.request(reallyUrl, query, 'get')
  },
  post: function (url, body) {
    console.log(url, 'url')
    return this.request(apis[url].url, body, 'post')
  },
  put: function (url, body) {
    return this.request(url, body, 'put')
  },
  delete: function (url, body) {
    return this.request(url, body, 'delete')
  },
  request: function (url, data, method) {
    return new Promise((resolve) => {
      Taro.request({
        url: getBaseUrl() + url, //仅为示例，并非真实的接口地址
        method,
        data: method !== 'get' ? data : null,
        header: {
          'content-type': 'application/json', // 默认值
        },
        success: function (res) {
          resolve(res.data)
        },
      })
    })
  },
}
export default $ajax
